<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 角色管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="description" clearable size="mini" style="width: 100px"    class="handle-select mr10" placeholder="角色名称" ></el-input>
                <el-button type="primary" icon="el-icon-search" @click="search" size="mini">搜索</el-button>
            </div>
            <el-button @click='toAdd'  v-if="$_has('role:add')" type="primary" size="mini" style="margin-bottom: 10px">添加角色</el-button>
            <el-button @click='batchDelete'  v-if="$_has('role:batchDelete')" type="primary" size="mini">批量删除</el-button>
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="40" ></el-table-column>

                <el-table-column prop="description" label="角色名称" width="180"  align="center">
                </el-table-column>
                <el-table-column prop="name" label="角色编码 "  align="center">
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180"  align="center">
                </el-table-column>
                <el-table-column prop="updateTime" label="修改时间" width="180"  align="center">
                </el-table-column>
                <el-table-column prop="available" label="状态"  align="center">
                    <template slot-scope="scope">
                        <span v-if="scope.row.available == false" style="color: red">禁用 </span>
                        <span v-if="scope.row.available == true" >启用</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="350">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text"   icon="el-icon-edit" v-if="$_has('role:edit')" @click="changeRole(scope.$index, scope.row)">修改</el-button>
                        <el-button size="mini" type="text"   @click="handleEdit(scope.$index, scope.row)"  >分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        @current-change="handleCurrentChange" :page-size="10" :pager-count="11" layout="prev, pager, next" :current-page="pageCount" :total="total"
                ></el-pagination>
            </div>
        </div>
        <el-dialog title="修改权限" :visible.sync="powerVisible" width="20%" :append-to-body='true' >
            <el-tree
                    :default-checked-keys="checkArr"
                    @check-change="handleCheckChange"
                    :data="menuArr"
                    show-checkbox
                    default-expand-all
                    node-key="id"
                    ref="tree"
                    highlight-current
                    size="big"
                    :props="defaultProps">
            </el-tree>
            <span slot="footer" class="dialog-footer">
			    <el-button type="primary" @click="CheckedKeys" >确 定</el-button>
			 </span>
        </el-dialog>
        <!--//add框-->
        <el-dialog title="添加角色" :visible.sync="dialogVisible" width="40%" :append-to-body='true'>
            <!--表单内容-->
            <el-form ref="form" :model="form" label-width="20%" :rules='rules' :hide-required-asterisk='true'>
                <el-form-item label="角色编码" prop='name'>
                    <el-input v-model="form.name" style="width: 60%"   size="mini"></el-input>
                </el-form-item>
                <el-form-item label="角色名称" prop='description'>
                    <el-input v-model="form.description" style="width: 60%"   size="mini"></el-input>
                </el-form-item>
                <el-form-item label="是否有效" prop='available'>
                    <el-select
                            class="size-full"
                            size="mini"
                            v-model="form.available"
                            placeholder="请选择"
                            clearable
                            style="width:60%"
                    >
                        <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class='deviceManage-el-form-item information-el-form-item'>
                    <el-button type="primary" @click="onSubmit">确定</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
    import getData from '../../../getData/api'
    export default {
        name: "roleManage",
        data(){
          return{
              powerVisible:false,//分配权限
              menuArr:[],//获得的权限数组
              checkArr:[],//选中的数组
              description:"",
              check:[],
              roleId:"",
              defaultProps: {
                  children: 'nodes',
                  label: 'name'
              },//el-tree配置
              options: [{
                  value: false,
                  label: '失效'
              }, {
                  value: true,
                  label: '生效'
              }],
              total:1,
              tableData:[],//表格DATA
              pageCount:1,//页数
              dialogVisible:false,//添加用户的弹窗
              form:{//添加的对象
                  id:'',
                  available:'',//状态
                  name:'',//角色编码
                  description:'',//角色名称
              },
              rules:{//必填校验
                  available: [{
                      required: true,
                      message: '状态不能为空',
                      trigger: 'blur'
                  }],
                  name: [{
                      required: true,
                      message: '角色编码不能为空',
                      trigger: 'blur'
                  }],
                  description:[{
                      required: true,
                      message: '角色名称不能为空',
                      trigger: 'blur'
                  }],
              },
              multipleSelection:[],
          }
        },
        methods:{
            //批量
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            //批量删除
            batchDelete(){
                this.$confirm('确定删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let ids=[];
                    Object.keys(this.multipleSelection).forEach((key) => {
                        ids.push(this.multipleSelection[key].id)
                    });
                    let params = {
                        "ids": ids,
                    };
                    let formData = new FormData();
                    Object.keys(params).forEach((key) => {
                        formData.append(key, params[key]);
                    });//转form-data
                    getData.roleRemove(formData)
                        .then(res => {
                            this.search()
                            if (res.status == 200) {
                                this.$message.success(res.message)
                            }
                        })
                })
            },
            //翻页触发
            handleCurrentChange(val) {
                //每次翻页都请求数据
                this.pageCount = val
                this.search()
            },
            //添加角色
            toAdd() {
                if (this.form.id!=''){
                    this.initFormData()
                }
                this.dialogVisible = true;//添加角色的弹窗
            },
            //分配权限
            handleEdit(index,row){

                this.roleId=row.id;
                this.getPowerData(row);
                // this.getCheckData(row);
                this.powerVisible=true;
            },
            handleCheckChange(a, b, c) {
                this.check=[];
                let check=this.$refs.tree.getCheckedKeys()
                let HalfCheck=this.$refs.tree.getHalfCheckedKeys();
                this.check=HalfCheck.concat(check)
                const anode = this.$refs.tree.getNode(a)
                !anode.checked ? this.findchildren(anode.parent) : ''
                console.log(anode.checked)
                console.log(this.check)
                // console.log(this.menuArr)
                // console.log(this.check)
            },
            findchildren(current) {
                const fnode = this.$refs.tree.getNode(current)
                if (!fnode.isLeaf) {
                    fnode.indeterminate = true
                    fnode.checked = true
                }
            },
            //分配
            CheckedKeys(){
                this.check=[];
                let check1=this.$refs.tree.getCheckedKeys()
                let HalfCheck=this.$refs.tree.getHalfCheckedKeys();
                this.check=HalfCheck.concat(check1)
                let check = this.check.join(",")
                let params = {
                    roleId:this.roleId,
                    resourcesId:check
                };
                let formData = new FormData();
                Object.keys(params).forEach((key) => {
                    formData.append(key, params[key]);
                });//转form-data
                getData.saveRoleResources(formData)
                    .then(res=>{
                        this.powerVisible=false
                        if (res.status==200){
                            this.$message.success(res.message+"，请刷新页面")
                            getData.findUserResources(params)//成功了重新获取一遍后台的权限列表
                                .then((res) => {
                                    if (res.status == 200) {
                                        for (let i = 0; i < res.data.length; i++) {
                                            if (res.data[i].nodes == null) {
                                                res.data[i].nodes = [];
                                            }
                                        }
                                        let btnPermission=[];
                                        let menuArr=res.data;
                                        //循环取出所有的按钮
                                        Object.keys(menuArr).forEach((key) => {
                                            if (menuArr[key].type=="button"){
                                                btnPermission.push(this.menuArr[key].permission)
                                            }
                                            if (menuArr[key].nodes!=null){
                                                Object.keys(menuArr[key].nodes).forEach((key1) => {
                                                    if (menuArr[key].nodes[key1].type=="button"){
                                                        btnPermission.push(menuArr[key].nodes[key1].permission)
                                                    }
                                                    if (menuArr[key].nodes[key1].nodes!=null){
                                                        Object.keys(menuArr[key].nodes[key1].nodes).forEach((key2) => {
                                                            if (menuArr[key].nodes[key1].nodes[key2].type=="button"){
                                                                btnPermission.push(menuArr[key].nodes[key1].nodes[key2].permission)
                                                            }
                                                        });
                                                    }
                                                });
                                            }
                                        });
                                        localStorage.setItem('btnPermission', JSON.stringify(btnPermission));
                                        localStorage.setItem('resourcesrList', JSON.stringify(res.data));//后台返回的权限
                                    }
                                })
                        }else {
                            this.$message.error(res.message)
                        }
                    })
            },
            //提交添加角色
            onSubmit() {
                //先校验form的必填项
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        let params = {
                            available: this.form.available,
                            name:this.form.name,
                            description: this.form.description,
                        }
                        // console.log(params)
                        let formData = new FormData();
                        Object.keys(params).forEach((key) => {
                            formData.append(key, params[key]);
                        });//转form-data，后台要求
                        if (this.form.id=='') {//id为空就是添加。不为空就是修改
                            getData.addRole(formData)
                                .then((res) => {
                                    this.search()
                                    this.dialogVisible = false;
                                    if (res.status==200){
                                        this.$message.success(res.message)
                                    }
                                })
                        }else {
                            getData.changeRole(formData)
                                .then((res) => {
                                    this.search()
                                    this.dialogVisible = false;
                                    if (res.status==200){
                                        this.$message.success(res.message)
                                    }
                                })
                        }
                    } else {
                        return false;
                    }});
                },
            //弹出修改角色
            changeRole(index,row){
                Object.keys(this.form).forEach(key => {
                    this.form[key] = row[key]
                })
                this.dialogVisible=true
                // console.log(this.form)
            },
            //获取权限列表
            getPowerData(row){
                this.menuArr=[];
                let params = {
                    rid:row.id,
                    "pageNumber":1,
                    "pageSize":1000,
                };
                let formData = new FormData();
                Object.keys(params).forEach((key) => {
                    formData.append(key, params[key]);
                });//转form-data
                getData.resourcesByRole(formData)
                    .then(res=>{
                      this.checkArr=[];
                        this.menuArr=res.data;
                        Object.keys(this.menuArr).forEach((key) => {
                            // if (this.menuArr[key].checked=="true"){
                            //     this.checkArr.push(this.menuArr[key].id)
                            // }
                            if (this.menuArr[key].nodes!=null){
                                Object.keys(this.menuArr[key].nodes).forEach((key1) => {
                                    // if (this.menuArr[key].nodes[key1].checked=="true"){
                                    //     this.checkArr.push(this.menuArr[key].nodes[key1].id)
                                    // }
                                    if (this.menuArr[key].nodes[key1].nodes!=null){
                                        Object.keys(this.menuArr[key].nodes[key1].nodes).forEach((key2) => {
                                            if (this.menuArr[key].nodes[key1].nodes[key2].checked=="true"){
                                                this.checkArr.push(this.menuArr[key].nodes[key1].nodes[key2].id)
                                            }
                                        });
                                    }
                                });
                            }

                        });
                        console.log(this.menuArr)
                        console.log( this.checkArr)
                        // for (let i=0;i<this.menuArr.length;i++) {
                        //     if (this.menuArr[i].checked=="true"){
                        //         this.check.push(this.menuArr[i].id)
                        //     }
                        //         // for(var k=0;k<this.menuArr[i].nodes[j].nodes.length;k++) {
                        //         //     if (this.menuArr[i].nodes[j].nodes[k].check==true){
                        //         //         this.check.push(this.menuArr[i].nodes[j].nodes[k].id)
                        //         //     }
                        //         // }
                        //     // }
                        // }
                        // console.log(this.checkArr)
                    })
            },
            //获取已选中的数组
            getCheckData(row){
                this.checkArr=[];
                let params = {
                    rid:row.id,
                    "pageNumber":1,
                    "pageSize":1000,
                };
                let formData = new FormData();
                Object.keys(params).forEach((key) => {
                    formData.append(key, params[key]);
                });//转form-data
                getData.resourcesByRole(formData)
                    .then(res=>{
                        this.checkArr=res.data
                    })
            },
            //请求角色List数据
            search(){
                let params = {
                    "pageNumber":this.pageCount,
                    "pageSize":10,
                    "description":this.description,
                };
                let formData = new FormData();
                Object.keys(params).forEach((key) => {
                    formData.append(key, params[key]);
                });//转form-data
                getData.roleList(formData)
                    .then(res=>{
                        // console.log(res)
                        this.tableData=res.rows
                        this.total=res.total
                    })
            },
            initFormData() {//清空新增修改之类的所有数据
                this.form={
                    id:'',
                    available:'',//状态
                    name:'',//角色编码
                    description:'',//角色名称
                }
            }
        },

        mounted(){
          this.search()
        },

    }
</script>

<style scoped>
    @import '~assets/styles/main.css';
    /*搜索框*/
    .handle-box {
        margin-bottom: 10px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .table {
        width: 100%;
        font-size: 14px;
    }
    .red {
        color: #ff0000;
    }
    .mr10 {
        margin-right: 10px;
    }
    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
    .del-dialog-cnt{
        font-size: 16px;
        text-align: center
    }
</style>
